package hangler

import (
	"dio-tech/cache"
	"dio-tech/model"
	"dio-tech/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func User(c *gin.Context) {
	name := c.PostForm("name")
	password := c.PostForm("password")
	if name == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段为空",
		})
		return
	}
	var user model.User
	redis_key := "user" + name
	str, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if str >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次 禁止登录",
		})
		return
	}
	err := model.DB.Where("name = ?", name).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "未找到该用户",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名错误",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if str == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次 封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return

}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var posts []model.Posts
	redis_key := "list" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		model.DB.Offset(offset).Limit(size).Find(&posts)
		json.Marshal(posts)
		cache.Rdb.Set(cache.Ctx, redis_key, result, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &posts)
	}
	var total int64
	model.DB.Model(&model.Posts{}).Count(&total)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"total": total,
			"posts": posts,
		},
	})
	return

}
